package cn.peach.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 把token放到浏览器的请求头中
        String token = request.getHeader("token");
        // 从redis中获取数据并判断token是否为空
        if(!StringUtils.isEmpty(token)){
            Object obj = redisTemplate.opsForValue().get(token);
            // 如果不为空 说明没过期 刷新时间
            if (obj != null){
                redisTemplate.opsForValue().set(token, obj, 30, TimeUnit.MINUTES);
                // 放行
                return true;
            }
        }
        // 如果过期
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        // 获取输出流
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }
}
